package com.example.spring.jpa.specification;

import com.example.spring.jpa.ast.PriorityOperation;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: orange
 * @create: 2023-07-24 20:46
 * @description:
 */
public class DateGenerate extends GlobalPredicate {
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("");

    @Override
    public Expression<Date> getExpression(GenerateApplicationContext context) {
        if (context.getPath() != null) {
            return context.getPath().as(Date.class);
        }
        return context.getRoot().get(context.getLeft()).as(Date.class);
    }

    @Override
    public Predicate doGenerate(GenerateApplicationContext context) throws ParseException {
        Date date = simpleDateFormat.parse(context.getRight());
        if (PriorityOperation.Equals.getOperation().equals(context.getOperation())) {
            return context.getBuilder().equal(getExpression(context), date);
        }
        if (PriorityOperation.NotEquals$1.getOperation().equals(context.getOperation())
                || PriorityOperation.NotEquals$2.getOperation().equals(context.getOperation())) {
            return context.getBuilder().notEqual(getExpression(context), date);
        }
        throw new RuntimeException(String.format("Date类型不支持%s运算符！", context.getOperation()));
    }
}
